﻿using Furion.DatabaseAccessor;
using Microsoft.Extensions.Logging;
using SqlSugar;
using Yitter.IdGenerator;

namespace tlBasic.Application.System
{
    public class SystemService : IDynamicApiController, ITransient
    {


        private readonly ILogger<SystemService> _logger;
        private readonly SqlSugarRepository<sys_Menu> _sysMenuRep;
        private readonly SqlSugarRepository<sys_DicType> _sysdictypeRep;
        private readonly SqlSugarRepository<sys_DicData> _sysdicdataRep;
        private readonly SqlSugarRepository<sys_AppInfo> _sysappinfoRep;
        private readonly ISysCacheService _cacheService;
        public SystemService(ILogger<SystemService> logger
            , SqlSugarRepository<sys_Menu> sysMenuRep
            , SqlSugarRepository<sys_DicType> sysdictypeRep
            , SqlSugarRepository<sys_DicData> sysdicdataRep
            , SqlSugarRepository<sys_AppInfo> sysappinfoRep
            , ISysCacheService cacheService)
        {
            _logger = logger;
            _sysMenuRep = sysMenuRep;
            _sysdictypeRep = sysdictypeRep;
            _sysdicdataRep = sysdicdataRep;
            _sysappinfoRep = sysappinfoRep;
            _cacheService = cacheService;
        }
        public string GetDescription()
        {
            return "让 .NET 开发更简单，更通用，更流行。";
        }


        #region 目录菜单
        /// <summary>
        /// 获取所有菜单
        /// </summary>
        /// <returns></returns>
        public Task<List<sys_Menu>> GetMenuTreeList()
        {
            var menuList = _sysMenuRep.AsQueryable()
                .OrderBy(u => u.Sort).ToTreeAsync(u => u.children, u => u.ParentId, 0);
            return menuList;
        }
        public Task<List<sys_Menu>> GetMenuList()
        {
            var menuList = _sysMenuRep.AsQueryable()
                .OrderBy(u => u.Sort).ToListAsync();
            return menuList;
        }
        /// <summary>
        /// 获取商户菜单
        /// </summary>
        /// <returns></returns>
        public Task<List<sys_Menu>> GetTenantMenuTreeList()
        {
            var menuList = _sysMenuRep.AsQueryable().Where(m => !m.IsSystem)
                .OrderBy(u => u.Sort).ToTreeAsync(u => u.children, u => u.ParentId, 0);
            return menuList;
        }
        /// <summary>
        /// 保存 
        /// </summary>
        /// <returns></returns>
        [SecurityDefine("sysmenu")]
        public void SaveMenu(sys_Menu input)
        {
            var oldCount = _sysMenuRep.AsQueryable().Where(m => m.PermissionKey.Equals(input.PermissionKey) && m.Id != input.Id).Count();

            if (input.Id > 0)
            {
                _sysMenuRep.Update(input);
            }
            else
            {
                _sysMenuRep.Insert(input);
            }
            _cacheService.DelByPattern(CacheConst.KeyPermission);
        }
        /// <summary>
        /// 复制 
        /// </summary>
        /// <param name="id"></param>
        [SecurityDefine("sysmenu")]
        public void CopyMenu(long id)
        {
            var info = _sysMenuRep.GetById(id);
            info.Id = YitIdHelper.NextId();
            info.Sort += 2;
            _sysMenuRep.Insert(info);

        }
        /// <summary>
        /// 删除 
        /// </summary>
        /// <param name="id"></param>
        [SecurityDefine("sysmenu")]
        public void DeleteMenu(long id)
        {
            var menuTreeList = _sysMenuRep.AsQueryable().ToChildList(u => u.ParentId, id);
            var menuIdList = menuTreeList.Select(u => u.Id).ToList();
            _sysMenuRep.AsUpdateable()
            .SetColumns(it => it.IsDeleted == true)
            .Where(it => menuIdList.Contains(it.Id))
            .ExecuteCommand();

        }
        #endregion

        #region 数据字典
        /// <summary>
        /// 获取字典分类
        /// </summary>
        /// <returns></returns>
        public Task<List<sys_DicType>> GetDicType()
        {
            return _sysdictypeRep.AsQueryable()
                .OrderBy(u => u.Sort).ToListAsync();
        }

        /// <summary>
        /// 保存字典分类
        /// </summary>
        /// <returns></returns>
        [SecurityDefine("sysdic")]
        public void SaveDicType(sys_DicType input)
        {
            var oldCount = _sysdictypeRep.AsQueryable().Where(m => m.Code.Equals(input.Code) && m.Id != input.Id).Count();
            if (oldCount > 0)
            {
                throw Oops.Bah("字典类别编码已存在");
            }
            if (input.Id > 0)
            {
                _sysdictypeRep.Update(input);
            }
            else
            {
                _sysdictypeRep.Insert(input);
            }
        }
        /// <summary>
        /// 删除字典分类
        /// </summary>
        /// <param name="id"></param>
        [SecurityDefine("sysdic")]
        [UnitOfWork]
        public void DeleteDicType(long id)
        {
            var type = _sysdictypeRep.GetById(id);
            type.IsDeleted = true;
            _sysdictypeRep.Update(type);
            _sysdicdataRep.AsUpdateable().SetColumns(it => it.IsDeleted == true)
            .Where(it => it.TypeCode.Equals(type.Code))
            .ExecuteCommand();
        }



        /// <summary>
        /// 获取字典数据
        /// </summary>
        /// <param name="typecodes"></param>
        /// <returns></returns>
        public Task<List<sys_DicData>> SearchDicData(List<string> typecodes)
        {
            var sqlStr = $@"SELECT A.*,B.Name AS TypeName FROM sys_DicData A INNER JOIN sys_DicType B ON A.TypeCode=B.Code";

            return _sysdicdataRep.AsSugarClient().SqlQueryable<sys_DicData>(sqlStr).WhereIF(typecodes != null && typecodes.Count > 0, m => typecodes.Contains(m.TypeCode))
                 .OrderBy(m => new { m.TypeCode, m.Sort }).ToListAsync();
        }

        /// <summary>
        /// 保存字典数据
        /// </summary>
        /// <returns></returns>
        [SecurityDefine("sysdic")]
        public void SaveDicData(sys_DicData input)
        {
            if (input.Id > 0)
            {
                _sysdicdataRep.Update(input);
            }
            else
            {
                _sysdicdataRep.Insert(input);
            }
        }
        /// <summary>
        /// 删除字典分类
        /// </summary>
        /// <param name="id"></param>
        [SecurityDefine("sysdic")]
        [UnitOfWork]
        public void DeleteDicData(long id)
        {
            _sysdicdataRep.AsUpdateable().SetColumns(it => it.IsDeleted == true)
            .Where(it => it.Id == id)
            .ExecuteCommand();
        }

        #endregion


        #region APP管理
        /// <summary>
        /// 查询App
        /// </summary>
        /// <returns></returns> 
        public Task<List<sys_AppInfo>> GetAppInfoList()
        {
            return _sysappinfoRep.AsQueryable().ToListAsync();
        }

        /// <summary>
        /// 根据包名查询app
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public sys_AppInfo GetAppInfo(string packageName)
        {
            return _sysappinfoRep.GetFirst(m => m.PackageName.Equals(packageName));
        }
        /// <summary>
        /// 保存 
        /// </summary>
        /// <returns></returns>
        [SecurityDefine("appinfo")]
        public void SaveAppInfo(sys_AppInfo input)
        {

            if (input.Id > 0)
            {
                _sysappinfoRep.Update(input);
            }
            else
            {
                _sysappinfoRep.Insert(input);
            }
        }

        /// <summary>
        /// 删除 
        /// </summary>
        /// <param name="id"></param>
        [SecurityDefine("appinfo")]
        public void DeleteAppInfo(long id)
        {
            _sysappinfoRep.AsUpdateable().SetColumns(m => m.IsDeleted == true).Where(m => m.Id == id).ExecuteCommand();
        }
        #endregion
    }
}
